#include <stdio.h>
#include <string.h>
#include "mqtt/mqtt.h"
#include "wifi.h"

typedef enum
{
    WIFI_SENSOR_TYPE_IP,      /* IP地址 */
    WIFI_SENSOR_TYPE_MASK,    /* 掩码 */
    WIFI_SENSOR_TYPE_GATEWAY, /* 网关 */
    WIFI_SENSOR_TYPE_RSSI,    /* 信号强度 */
    WIFI_SENSOR_TYPE_SSID,    /* SSID */
    WIFI_SENSOR_TYPE_MAC,     /* MAC地址 */
    WIFI_SENSOR_TYPE_MAX,
} dvc_sensor_type_t;

static uint8_t get_sensor_state(void *user_data, uint8_t id, char *buf, uint8_t len)
{
    if (!wifi_stack || id >= WIFI_SENSOR_TYPE_MAX)
        return 0;
    wifi_stack_t wifi = wifi_stack;
    if (id == WIFI_SENSOR_TYPE_IP)
        return snprintf(buf, len, "%s", wifi->ip);
    else if (id == WIFI_SENSOR_TYPE_MASK)
        return snprintf(buf, len, "%s", wifi->netmask);
    else if (id == WIFI_SENSOR_TYPE_GATEWAY)
        return snprintf(buf, len, "%s", wifi->gw);
    else if (id == WIFI_SENSOR_TYPE_RSSI)
    {
        wifi_ap_record_t ap_info = {0};
        esp_wifi_sta_get_ap_info(&ap_info);
        return snprintf(buf, len, "%d", ap_info.rssi);
    }
    else if (id == WIFI_SENSOR_TYPE_SSID)
        return snprintf(buf, len, "%s", wifi->sta_ssid);
    else if (id == WIFI_SENSOR_TYPE_MAC)
    {
        uint8_t mac[6];
        esp_wifi_get_mac(WIFI_IF_STA, mac);
        return snprintf(buf, len, MACSTR, MAC2STR(mac));
    }
    return 0;
}

ADD_MQTT_ENTITY_DEVICE_TRACKER(WIFI_SENSOR_TYPE_IP, wifi_ip, get_sensor_state, NULL);
ADD_MQTT_ENTITY_DEVICE_TRACKER(WIFI_SENSOR_TYPE_MASK, wifi_mask, get_sensor_state, NULL);
ADD_MQTT_ENTITY_DEVICE_TRACKER(WIFI_SENSOR_TYPE_GATEWAY, wifi_gateway, get_sensor_state, NULL);
ADD_MQTT_ENTITY_SENSOR(WIFI_SENSOR_TYPE_RSSI, wifi_rssi, NULL, get_sensor_state, NULL);
// ADD_MQTT_ENTITY_DEVICE_TRACKER(WIFI_SENSOR_TYPE_RSSI, wifi_rssi, get_sensor_state, NULL);
ADD_MQTT_ENTITY_DEVICE_TRACKER(WIFI_SENSOR_TYPE_SSID, wifi_ssid, get_sensor_state, NULL);
ADD_MQTT_ENTITY_DEVICE_TRACKER(WIFI_SENSOR_TYPE_MAC, wifi_mac, get_sensor_state, NULL);